<?php

namespace zhtfrontend\controllers;


use common\components\helpers\Fun;
use common\models\datas\Cate;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use zhtfrontend\models\datas\PricePackage;
use yii\web\Response;
use yii\widgets\ActiveForm;

class PricepackageController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $model = PricePackage::find()->orderBy('id DESC');
        $pageSize = 12;
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $pageSize]);
        !empty(\Yii::$app->request->get('page')) ? $pages->page = \Yii::$app->request->get('page') - 1 : 0;
        $data = $model->offset($pages->offset)->limit($pages->limit)->all();

        $data = Fun::asArray($data,['operate']);


        return $this->render('index',['data'=>$data,'page'=>$pages]);
    }

    public function actionCreate(){
        $model = new PricePackage();
        $model->is_frequency = 1;
        $model->is_activity = 0;

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            if($model->save(false)){
                return $this->redirectMessage(\Yii::t('zhtfrontend','保存成功！'),Fun::url('pricepackage/index'));
            }
        }

        return $this->render('create',['model'=>$model]);
    }

    public function actionUpdate(){
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend','信息不存在'));
        }
        $model = PricePackage::findOne($id);
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            if($model->save(false)){
                return $this->redirectMessage(\Yii::t('zhtfrontend','修改成功！'),Fun::url('pricepackage/index'));
            }
        }

        return $this->render('create',['model'=>$model]);
    }


}
